package com.ty.user.starter.config;

import com.ty.user.starter.properties.UserMgtProperties;
import com.ty.user.starter.shiro.UserMgtRealm;
import com.ty.user.starter.shiro.filter.UserMgtAuthenticationFilter;
import com.ty.user.starter.shiro.filter.UserMgtPermissionsAuthorizationFilter;
import com.ty.user.starter.shiro.filter.UserMgtRolesAuthorizationFilter;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.Authenticator;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authc.pam.FirstSuccessfulStrategy;
import org.apache.shiro.authc.pam.ModularRealmAuthenticator;
import org.apache.shiro.cache.MemoryConstrainedCacheManager;
import org.apache.shiro.mgt.DefaultSessionStorageEvaluator;
import org.apache.shiro.mgt.DefaultSubjectDAO;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.CollectionUtils;

import javax.servlet.Filter;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * shiro安全认证配置
 */
@Slf4j
@Configuration
public class ShiroConfig {

    /**
     * 开启shiro提供的权限相关的注解
     *
     * @param securityManager 安全管理器
     **/
    @Bean
    public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
        AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
        authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
        return authorizationAttributeSourceAdvisor;
    }


    @Bean
    public DefaultWebSecurityManager securityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealms(Collections.singletonList(userMgtRealm()));
        //关闭shiro自带的session
        DefaultSubjectDAO subjectDAO = new DefaultSubjectDAO();
        DefaultSessionStorageEvaluator defaultSessionStorageEvaluator = new DefaultSessionStorageEvaluator();
        defaultSessionStorageEvaluator.setSessionStorageEnabled(true);
        subjectDAO.setSessionStorageEvaluator(defaultSessionStorageEvaluator);
        securityManager.setSubjectDAO(subjectDAO);
        securityManager.setCacheManager(new MemoryConstrainedCacheManager());
        return securityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilter(DefaultWebSecurityManager securityManager, UserMgtProperties properties) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        Map<String, Filter> filterMap = new HashMap<>();

        //配置拦截器
        filterMap.put("authc", new UserMgtAuthenticationFilter());
        filterMap.put("perms", new UserMgtPermissionsAuthorizationFilter());
        filterMap.put("roles", new UserMgtRolesAuthorizationFilter());

        shiroFilterFactoryBean.setFilters(filterMap);
        //配置拦截路由
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //设置拦截
        shiroFilterFactoryBean.setFilterChainDefinitionMap(getFilterChainDefinitionMap(properties));
        return shiroFilterFactoryBean;
    }

    /**
     * 设置拦截链表
     *
     * @return 拦截信息列表
     */

    public Map<String, String> getFilterChainDefinitionMap(UserMgtProperties properties) {
        Map<String, String> filterChainDefinitionMap = new ConcurrentHashMap<>();

        if (!CollectionUtils.isEmpty(Arrays.asList(properties.getAnons()))) {
            log.info("开始设置无需认证权限路径");
            for (String anon : properties.getAnons()) {
                log.info("--> {}", anon);
                filterChainDefinitionMap.put(anon, "anon");
            }
        } else {
            log.warn("未设置无需认证权限路径[{shiro.anons}]");
        }

        /* 登录,登出等服务请求路径放开安全认证 */
        filterChainDefinitionMap.put("/mgt/shiro/**", "anon");
        /* 除上述之外的其他请求路径皆进行安全认证 */
        filterChainDefinitionMap.put("/**", "authc");
        return filterChainDefinitionMap;
    }

    @Bean
    public UserMgtRealm userMgtRealm() {
        UserMgtRealm userMgtRealm = new UserMgtRealm();
        userMgtRealm.setCredentialsMatcher(hashedCredentialsMatcher());
        return userMgtRealm;
    }


    @Bean
    public HashedCredentialsMatcher hashedCredentialsMatcher() {
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("MD5");
        hashedCredentialsMatcher.setHashIterations(2);
        return hashedCredentialsMatcher;
    }

    /**
     * 初始化Authenticator
     */
    @Bean
    public Authenticator authenticator() {
        ModularRealmAuthenticator authenticator = new ModularRealmAuthenticator();
        authenticator.setAuthenticationStrategy(new FirstSuccessfulStrategy());
        return authenticator;
    }

}
